<template>
	<div :ref='refName' class="swiper-container">
		<div class="swiper-wrapper clear" :ref="sliderGroup">
			<slot></slot>
		</div>
	</div>
</template>

<script>
	import BScroll from 'better-scroll'
	export default {
		name: 'ScrollView',
		props: {
			probeType: {
				type: Number,
				default: 2
			},
			click: {
				type: Boolean,
				default: true
			},
			scrollX: {
				type: Boolean,
				default: false

			},
			scrollY: {
				type: Boolean,
				default: false

			},
			lowerThreshold: {
				type: Number,
				default: 50
			},

			listenScroll: {
				type: Boolean,
				default: false
			},
			refName: {
				type: String,
				default: 'swiper-wrapper'
			},
			data: {
				type: Array,
				require: true
			}
		},
		data() {
			return {
				isLoading: false, 
				setScrollX: true,
				setScrollY: false,
				sliderGroup: '',
				sliderGroupWidth: '',
				wrapwidth: ''
			}
		},
		mounted() {
			this.sliderGroup = this.refName + "-slider-group";
			this.$nextTick(() => {
				this._initScroll();
				setTimeout(()=>{
					this._refresh()
				})
			}); 
 
		},
		watch:{
			
		},
		methods: {
			_initScroll() {
				var refName = this.refName;
				var _this = this
				if(!_this.$refs[refName]) {
					return;
				}
				
				if(_this.scrollX) {
					_this._setSliderWidth(); 
				}
				if(!_this.scroll) {
					_this.scroll = new BScroll(_this.$refs[refName], {
						probeType: _this.probeType,
						click: _this.click,
						scrollX: _this.scrollX,
						scrollY: _this.scrollY
					})
				} else {
					console.log(999)  
//					this._refresh()  
				} 
				
				var	maxScrollX = this.scroll.maxScrollX
				_this.scroll.on('scroll', (pos) => {
					if(_this.listenScroll) {
						_this.$emit('scroll', pos)
					}
					if(_this.scrollX) {
						if(pos.x  - maxScrollX < this.lowerThreshold) {
							_this._bindscrolltolower();
						}
					}
				})
			},
			_refresh() {
				if(this.scroll) {	
					//
				 this._setSliderWidth();
				 this.scroll.refresh();
				 
				}
			},
			_bindscrolltolower(){
				if(!this.isLoading) {
					this.$emit('bindscrolltolower')
				}
			},
			_setSliderWidth(isResize) {
				if(!this.scrollX){
					return
				}
				var sliderGroup = this.sliderGroup
				this.children = this.$refs[sliderGroup].children;
				let width = 0;
				for(let i = 0; i < this.children.length; i++) {
					width += (this.children[i].offsetWidth + 1);
				}
				this.sliderGroupWidth = width
				this.$refs[this.sliderGroup].style.width = width + "px"
			}
		}
	}
</script>

<style lang="scss" scoped>
	.swiper-container{
		overflow: hidden;
	}
</style>